import { UserAuth } from '../../utils/hooks';
import NotAuth from '../../components/NotAuth';
import React from 'react';
import { Layout, message, List, Button, Row, Col, Progress, Spin } from 'antd';
import { useState, useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';
import { selectUser } from '../../redux/Slice/userSlice';
import { Content, Header } from 'antd/lib/layout/layout';
import { importsExcel } from '../../utils/excel';
import axios from 'axios';
import * as moment from 'moment';
import Config, { XKLYmap, JFKMmap, XZmap, SYFXmap, GXMSmap } from '../../Config';
const InBatch = () => {
  const [curCount, SetCount] = useState(0);
  const [loading, SetLoading] = useState(false);
  const [cost, SetCost] = useState(0);
  const [size, Setsize] = useState(0);
  const [UploadData, SetUpdata] = useState([]);
  const [start, SetStart] = useState(Date.now());
  const [errData, SetErr] = useState([]);
  let websocket = null;
  let username = useSelector(selectUser);
  useEffect(() => {
    if ('WebSocket' in window) {
      websocket = new WebSocket(Config.baseWebSocketUrl + username);
      websocket.onopen = event => {};

      websocket.onmessage = event => {
        console.log(event.data);
        let webData = event.data;
        let jsonData = JSON.parse(webData);
        console.log(jsonData);
        if (jsonData.err !== undefined) {
          let arr = errData;
          jsonData.cur += 2;
          arr.push(jsonData);
          SetErr(arr);
        } else {
          // let cur = parseInt(webData);
          SetCount(((jsonData.cur / jsonData.size) * 100).toFixed(2));
          if (jsonData.cur == jsonData.size) {
            console.log(errData);
            let end = Date.now();
            message.success('导入成功,耗时' + (end - start) / 1000 + '秒', 2, () => {
              SetCost((end - start) / 1000);
              SetLoading(false);
            });
          }
          // console.log(((cur + 1) / size) * 100);
        }
      };
    } else {
      message.alert('浏览器不支持websocket,无法使用消息功能');
    }
    return () => {
      if (websocket !== null) {
        websocket.close();
      }
    };
  }, []);

  return (
    <>
      <Layout>
        <Header
          style={{
            borderRadius: '5px 5px 0px 0px',
            height: '40px',
            padding: '0px 15px',
            margin: '0px 0px',
            backgroundColor: 'white',
            textAlign: 'left',
            lineHeight: '40px',
          }}
        >
          <h3>仪器录入</h3>
        </Header>
        <Content style={{ padding: '10px 20px', backgroundColor: 'white' }}>
          <Spin spinning={loading}>
            <Row>
              <Col span={6}>
                <input
                  type="file"
                  accept=".xls,.xlsx"
                  style={{ float: 'left' }}
                  onChange={e => {
                    SetErr([]);
                    importsExcel(e).then(
                      function (data) {
                        Setsize(data.length);
                        let arr = [];
                        for (let i = 0; i < data.length; i++) {
                          if (XKLYmap.get(data[i].XKLY) === undefined) {
                            arr.push({
                              cur: i + 1,
                              err: '相关领域字典值错误',
                            });
                          }
                          if (JFKMmap.get(data[i].JFKM) === undefined) {
                            arr.push({
                              cur: i + 1,
                              err: '经费科目字典值错误',
                            });
                          }
                          if (XZmap.get(data[i].XZ) === undefined) {
                            arr.push({
                              cur: i + 1,
                              err: '现状字典值错误',
                            });
                          }
                          if (SYFXmap.get(data[i].SYFX) === undefined) {
                            arr.push({
                              cur: i + 1,
                              err: '现状字典值错误',
                            });
                          }
                          if (GXMSmap.get(data[i].GXMS) === undefined) {
                            arr.push({
                              cur: i + 1,
                              err: '共享模式字典值错误',
                            });
                          }
                          if (typeof data[i].SL !== 'number') {
                            arr.push({
                              cur: i + 1,
                              err: '数量类型错误',
                            });
                          }
                          if (typeof data[i].SFBZ !== 'number') {
                            arr.push({
                              cur: i + 1,
                              err: '收费标准类型错误',
                            });
                          }
                          data[i].imgUrl =
                            'https://instrumentsys.oss-cn-beijing.aliyuncs.com/instrumentImg/noImg.png';
                          data[i].registerName = username;
                          data[i].registerTime = moment().format('YYYY-MM-DD HH:mm:ss');
                          data[i].departmentId = '1 4';
                          data[i].placeId = '1 4';
                          data[i].GLR = 1;
                          data[i].state = 1;
                        }
                        SetErr(arr);
                        SetUpdata(data);
                      },
                      function (err) {
                        console.log(err);
                      }
                    );
                  }}
                />
              </Col>
              <Col span={6}>
                <Button
                  onClick={() => {
                    SetLoading(true);
                    SetStart(Date.now());
                    console.log(UploadData);
                    axios
                      .post(Config.baseURL + '/instrument/batchRegister', {
                        batchInstrument: UploadData,
                      })
                      .then(res => {
                        if (res.data.code == 1) {
                        } else {
                          message.error('导入失败' + res.data.message, 2);
                          SetLoading(false);
                        }
                      })
                      .catch(err => {
                        message.error('字段与数据不匹配', 2);
                        console.log(err);
                        SetLoading(false);
                      });
                  }}
                  type="primary"
                  size="large"
                >
                  上传
                </Button>
              </Col>
              <Col span={2}>
                <Button
                  type="primary"
                  size="large"
                  href="https://instrumentsys.oss-cn-beijing.aliyuncs.com/template/Intemplate.xlsx"
                  target="_blank"
                >
                  下载模板
                </Button>
              </Col>
            </Row>
          </Spin>
          <Row style={{ marginTop: '40px' }}>
            <Col span={12}>
              <Progress
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
                percent={curCount}
              />
            </Col>
            <Col span={4}>耗时： {cost} 秒</Col>
          </Row>
          <Row>
            <List
              header="错误信息"
              itemLayout="horizontal"
              dataSource={errData}
              style={{
                height: '600px',
                width: '900px',
                marginTop: '40px',
                overflowY: 'auto',
              }}
              renderItem={item => (
                <List.Item>
                  <List.Item.Meta
                    title={'错误数据序号： ' + item.cur}
                    description={'错误原因 ' + item.err}
                  />
                </List.Item>
              )}
            ></List>
          </Row>
        </Content>
      </Layout>
    </>
  );
};

export default () => {
  const { authority } = UserAuth('InBatch');
  return <>{authority ? <InBatch /> : <NotAuth />}</>;
};
